//
//  Image.m
//  Void Dead
//
//  Created by Sidney Just on 06.07.09.
//  Copyright 2009 by Sidney Just
//  This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; 
//  either version 3 of the License, or (at your option) any later version.
//  
//  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty 
//  of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//  

#import "Image.h"
#import "color.h"

@implementation VD_Image
@synthesize width, height;

- (id)init {
	if(self = [super init])
	{
		data = NULL;
	}
	return self;
}

- (void)dealloc {
	[self closeBitmap];
	[super dealloc];
}

- (CGContextRef)createARGBBitmapContextFromImage:(CGImageRef)inImage {
	
	CGContextRef    context = NULL;
	CGColorSpaceRef colorSpace;
	void *          bitmapData;
	int             bitmapByteCount;
	int             bitmapBytesPerRow;
	
	size_t pixelsWide = CGImageGetWidth(inImage);
	size_t pixelsHigh = CGImageGetHeight(inImage);
	
	bitmapBytesPerRow   = (pixelsWide * 4);
	bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh);
	
	colorSpace = CGColorSpaceCreateDeviceRGB();
	
	if (colorSpace == NULL)
	{
		return NULL;
	}
	
	bitmapData = malloc( bitmapByteCount );
	if (bitmapData == NULL)
	{
		CGColorSpaceRelease( colorSpace );
		return NULL;
	}
	
	context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst);
	if (context == NULL)
	{
		free (bitmapData);
	}
	
	CGColorSpaceRelease( colorSpace );
	
	return context;
}

- (void)lockBitmap:(NSString *)file {
	[self closeBitmap];
	
	CGImageRef inImage = [UIImage imageNamed:file].CGImage;
	CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
	if (cgctx == NULL) { return; }
	
    width = CGImageGetWidth(inImage);
	height = CGImageGetHeight(inImage);
	CGRect rect = {{0,0},{width,height}}; 
	
	CGContextDrawImage(cgctx, rect, inImage);
	
	data = CGBitmapContextGetData (cgctx);
	CGContextRelease(cgctx);
}


- (void)closeBitmap {
	if(data != NULL) 
	{
		free(data); 
		data = NULL;
	}
}

- (VD_Color *)getBitmapColor:(CGPoint)point {
	VD_Color *tempCol = [[VD_Color alloc] init];
	
	if (data != NULL) {
		int offset = 4*((width*round(point.y))+round(point.x));
		tempCol.alpha = data[offset];
		tempCol.red = data[offset+1];
		tempCol.green = data[offset+2];
		tempCol.blue = data[offset+3];
	} else {
		return NULL;
	}
	
	return tempCol;
}


@end
